package rpcjson

import (
	"context"
	"github.com/docker/docker/api/types"
	"gykjgit.dccnet.com.cn/chain/swarm/client"
	"gykjgit.dccnet.com.cn/chain/swarm/rpcjson/model"
	"io/ioutil"
	"strconv"
)

type Service struct{}

// List 获取服务信息
func (Service) Create(req model.ReqServiceCreate, resp *model.RespServiceCreate) error {
	response, err := client.ObtainClient().ServiceCreate(context.Background(), req.Service, req.Options)
	if nil != err {
		return err
	}
	resp.Response = response
	return nil
}

// Logs 获取服务日志
func (Service) Logs(req model.ReqServiceLogs, resp *model.RespServiceLogs) error {
	body, err := client.ObtainClient().ServiceLogs(context.Background(), req.ServiceID, types.ContainerLogsOptions{
		ShowStdout: true,
		ShowStderr: true,
		Timestamps: req.Timestamps,                          // 显示时间戳
		Details:    req.Details,                             // 显示提供给日志的额外细节
		Follow:     req.Follow,                              // 跟踪日志输出
		Tail:       req.Tail,                                // 从日志末尾显示的行数(默认为“all”)
		Since:      strconv.FormatInt(req.Since.Unix(), 10), // "1589772560.000000001"
		Until:      strconv.FormatInt(req.Until.Unix(), 10), // "1589772720.000000001"
	})
	if nil != err {
		return err
	}
	defer func() { _ = body.Close() }()
	var data []byte
	if data, err = ioutil.ReadAll(body); nil != err {
		return err
	}
	resp.Data = data
	return nil
}

// List 获取服务信息
func (Service) List(req model.ReqServiceList, resp *model.RespServiceList) error {
	services, err := client.ObtainClient().ServiceList(context.Background(), req.Options)
	if nil != err {
		return err
	}
	resp.Services = services
	return nil
}

// Process List the tasks of one or more services
func (Service) Process(req model.ReqServiceProcess, resp *model.RespServiceProcess) error {
	tasks, err := client.ObtainClient().TaskList(context.Background(), types.TaskListOptions{Filters: req.Filters})
	if nil != err {
		return err
	}
	resp.Tasks = tasks
	return nil
}

// Remove Remove one or more services
func (Service) Remove(req model.ReqServiceRemove, _ *model.RespServiceRemove) error {
	return client.ObtainClient().ServiceRemove(context.Background(), req.ServiceID)
}

// Update Update a service
func (Service) Update(req model.ReqServiceUpdate, resp *model.RespServiceUpdate) error {
	swarmInfo, err := client.Obtain().Swarm().Inspect()
	if nil != err {
		return err
	}
	var response types.ServiceUpdateResponse
	if response, err = client.ObtainClient().ServiceUpdate(context.Background(), req.ServiceID, swarmInfo.Version, req.Service, req.Options); nil != err {
		return err
	}
	resp.Response = response
	return nil
}

// Inspect 获取服务信息
func (Service) Inspect(req model.ReqServiceInspect, resp *model.RespServiceInspect) error {
	service, data, err := client.ObtainClient().ServiceInspectWithRaw(context.Background(), req.ServiceID, types.ServiceInspectOptions{InsertDefaults: req.InsertDefaults})
	if nil != err {
		return err
	}
	resp.Service = service
	resp.Data = data
	return nil
}
